package com.bobo.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.bobo.insertSale.InsertSale;
import com.bobo.service.factory.ServiceFactory;
import com.bobo.service.impl.ImportExcelUtil;
import com.bobo.services.HandleService;
import com.bobo.vo.Admin;
import com.bobo.vo.InfoVo;
import com.bobo.vo.Product;
import com.bobo.vo.Sale;
import com.bobo.vo.User;
import com.bobo.vo.extension.CityProductProfit;
import com.bobo.vo.extension.Extension;
import com.bobo.vo.extension.ProductListExtension;
import com.bobo.vo.extension.ProductSaleExtension;

@Controller
@RequestMapping("/adminHandle")
public class AdminHandleController extends Control{
	
	@RequestMapping("/uploadPage")
	public String uploadPage() {
		return "/WEB-INF/jsp/upload.jsp";
	}
	
	//spring提供的文件上传的方法速度快
	@RequestMapping("/upload")
	public String upload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException {
			HandleService handleService = ServiceFactory.getHandleService();
			boolean inserted = false;
			if(file != null) {
System.out.println("文件上传控制层！！！！！！！！！！！！！");
			String fileName = file.getOriginalFilename();
			System.out.println("文件名：" + fileName);
			

		InputStream in =null;
		Map<String, List<List<List<Object>>>> map = null;
//			MultipartFile file = multipartRequest.getFile("upfile");
		if(file.isEmpty()){
			try {
				throw new Exception("文件不存在！");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
 		in = file.getInputStream();
 		
		try {
			map = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());
		} catch (Exception e) {
			e.printStackTrace();
		}
		in.close();
		List<List<List<Object>>> listSheet = null;
		System.out.println(map.keySet());
		for(String key: map.keySet()) {
			
			if("User".equals(key)) {
				listSheet = map.get("User");
				List<List<Object>> listRow = listSheet.get(0);
				System.out.println("key: " + key + listRow.size());
				List<User> users= new ArrayList<User>();
				for(int i = 0; i < listRow.size(); i++) {
						User user = new User();
						List<Object> listCells = listRow.get(i);
						
						user.setId(Integer.parseInt(listCells.get(0).toString()));
						user.setUserName(listCells.get(1).toString());
						user.setAddress(listCells.get(2).toString());
						user.setBirthday(listCells.get(3).toString());
						user.setSex(listCells.get(4).toString());
						
//							inserted = handleService.inserted(user);
//							System.out.println(inserted + "================");
						users.add(user);
						System.out.println(user);
				}
				inserted = handleService.insertUserBatch(users);
				System.out.println(inserted + "================");
			}
			if("Product".equals(key)) {
				listSheet = map.get("Product");
				List<List<Object>> listRow = listSheet.get(1);
				System.out.println("key: " + key + listSheet.get(1).size());
				List<Product> products = new ArrayList<Product>();
				for(int i = 0; i < listRow.size(); i++) {
						Product product = new Product();
						List<Object> listCells = listRow.get(i);
						
						product.setId(Integer.parseInt(listCells.get(0).toString()));
						product.setProductName(listCells.get(1).toString());
						product.setCategory(listCells.get(2).toString());
						product.setOcost(listCells.get(3).toString());
						product.setDanwei(listCells.get(4).toString());
						
//							inserted = handleService.inserteProduct(product);
//							System.out.println(inserted + "================");
						products.add(product);
						
						System.out.println(product);
				}
				System.out.println(products.size()+ "=====================集合大小");
				inserted = handleService.insertProductBatch(products);
				System.out.println(inserted + "================");
			}
			if("Sale".equals(key)) {
				listSheet = map.get("Sale");
				List<List<Object>> listRow = listSheet.get(2);
				System.out.println("key: " + key + listSheet.get(2).size());
				//定义一个list装生成的Sale
				List<Sale> sales = new ArrayList<Sale>();
				for(int i = 0; i < listRow.size(); i++) {
						Sale sale = new Sale();
						List<Object> listCells = listRow.get(i);
						sale.setDate(listCells.get(0).toString());
						sale.setUserId(Integer.parseInt(listCells.get(1).toString()));
						sale.setProductId(Integer.parseInt(listCells.get(2).toString()));
						sale.setCcost(listCells.get(3).toString());
						sale.setSaleCount(listCells.get(4).toString());
						
//							inserted = handleService.inserteSale(sale);
//							System.out.println(inserted + "================");
						//把sale装在list中
						sales.add(sale);
						System.out.println(sale);
				}
				int num = InsertSale.insert(sales);
				System.out.println(inserted + "================" + num);
			}
			System.out.println(key);
			
		}
		
		}
		if(inserted) {
			return "redirect:/jsp/success.html";
		}else {
			return "redirect:/jsp/err.html";
		}
	}
	
	@RequestMapping("/userList")
	public String showUserList(HttpServletRequest request, HttpSession session) {
		String address = this.isNull(request, session, "/WEB-INF/jsp/userList.jsp");
		HandleService handleService = ServiceFactory.getHandleService();
		if("/WEB-INF/jsp/userList.jsp".equals(address)) {
			List<User> users = handleService.findUserAll();
			request.setAttribute("users", users);
			return "/WEB-INF/jsp/userList.jsp";
		}
		return address;
	}
	
	@RequestMapping("/userBuyList")
	public String findUserBuyList(HttpServletRequest request, HttpSession session,
			@RequestParam("id")int id) {
		String address = this.isNull(request, session, "/WEB-INF/jsp/userBuyList.jsp");
		HandleService handleService = ServiceFactory.getHandleService();
		if("/WEB-INF/jsp/userBuyList.jsp".equals(address)) {
			if(id != 0) {
				List<Extension> extensions = handleService.findUserBuyList(id);
				if(extensions != null) {
					request.setAttribute("extensions", extensions);
				} else {
					request.setAttribute("errMsg", "该用户还没有购买任何商品");
				}
				
				return "/WEB-INF/jsp/userBuyList.jsp";
			}
			
			
		}
		return address;
	}
	@RequestMapping("/productList")
	public String productList(HttpServletRequest request, HttpSession session) {
		String address = this.isNull(request, session, "/WEB-INF/jsp/productList.jsp");
		HandleService handleService = ServiceFactory.getHandleService();
		if("/WEB-INF/jsp/productList.jsp".equals(address)) {
			List<ProductSaleExtension> productSaleExtensions = handleService.findProductList();
			if(productSaleExtensions != null) {
				List<ProductSaleExtension> productSaleExtensions2 = formatProductSaleExtension(productSaleExtensions);
				request.setAttribute("productSaleExtensions", productSaleExtensions2);
				return address;
			} else {
				request.setAttribute("errMsg", "商品列表为空");
				return address;
			}
			
		}
		return address;
	}
	
	//分页后的产品列表
	@RequestMapping("/productList2")
	public String productList2(HttpServletRequest request, HttpSession session, String page) {
		String address = this.isNull(request, session, "/WEB-INF/jsp/productList2.jsp");
		HandleService handleService = ServiceFactory.getHandleService();
		if("/WEB-INF/jsp/productList2.jsp".equals(address)) {
			//拿到商品总数量productNum
			int productNum = handleService.findProductNum_service();
			int pageCount = 0;
			if(productNum >= 0) {
				System.out.println(productNum);
				request.setAttribute("productNum", productNum);
				//page的数量
				pageCount= (int)Math.ceil(productNum/100.0);
				request.setAttribute("pageCount", pageCount);
			}
			
			if(page == null || Integer.parseInt(page) <= 1) {
				page = "1";
				request.setAttribute("page", 1);
			} else if(Integer.parseInt(page) >pageCount){
				page = String.valueOf(pageCount);
				request.setAttribute("page", pageCount);
			} else {
				request.setAttribute("page", Integer.parseInt(page));
			}
			
			//拿到对应page下的商品
			List<ProductListExtension> productListExtensions = handleService.findCityProductProfitList2(Integer.parseInt(page));
			if(productListExtensions != null) {
				for(ProductListExtension productListExtension: productListExtensions) {
					System.out.println(productListExtension);
				}
				request.setAttribute("productListExtensions", productListExtensions);
			}
		} else {
			request.setAttribute("errMsg", "商品列表为空");
		}
		return address;
	}
	
	public List<ProductSaleExtension> formatProductSaleExtension(List<ProductSaleExtension> productSaleExtensions){
		DecimalFormat format = new DecimalFormat("0.00");
		for(ProductSaleExtension productSaleExtension: productSaleExtensions) {
			productSaleExtension.setDccost(Double.parseDouble(format.format(Double.parseDouble(productSaleExtension.getCcost()))));
//			productSaleExtension.setDucount(Double.parseDouble(format.format(Double.parseDouble(productSaleExtension.getUcount()))));
			productSaleExtension.setProfit((Double.parseDouble(format.format(
					Double.parseDouble(productSaleExtension.getCcost())-Double.parseDouble(productSaleExtension.getOcost())
					))));
		}
		
		return productSaleExtensions;
	}
	
	@RequestMapping("/productBuyDetail")
	public String productDetail(HttpServletRequest request, HttpSession session,int id) {
		String address = this.isNull(request, session, "/WEB-INF/jsp/productBuyDetail.jsp");
		HandleService handleService = ServiceFactory.getHandleService();
		if("/WEB-INF/jsp/productBuyDetail.jsp".equals(address)) {
			List<Extension> extensions = handleService.findProductBuyDetail(id);
			if(extensions != null) {
				request.setAttribute("extensions", extensions);
				return address;
			} else {
				request.setAttribute("errMsg", "改商品无人购买！");
				return address;
			}
			
		}
		return address;
	}
	
	@RequestMapping("/cityList")
	public String cityList(HttpServletRequest request, HttpSession session) {
		String address = this.isNull(request, session, "/WEB-INF/jsp/cityList.jsp");
		HandleService handleService = ServiceFactory.getHandleService();
		if("/WEB-INF/jsp/cityList.jsp".equals(address)) {
			List<User> users = handleService.findCityList();
			if(users != null) {
				request.setAttribute("users", users);
				return address;
			} else {
				request.setAttribute("errMsg", "当前没有任何城市的人购买过产品！");
				return address;
			}
		}
		return address;
	}
	
	@RequestMapping("/cityProductProfitList")
	public String cityProductProfitList(HttpServletRequest request, HttpSession session,
			String city) {
		String city2 = "";
		try {
			city2=new String((request.getParameter("city")).getBytes("iso-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String address = this.isNull(request, session, "/WEB-INF/jsp/cityProductProfitList.jsp");
		HandleService handleService = ServiceFactory.getHandleService();
		if("/WEB-INF/jsp/cityProductProfitList.jsp".equals(address)) {
			List<CityProductProfit> cityProductProfits = handleService.findCityProductProfitList(city2);
			List<CityProductProfit> cityProductProfits2 = handleService.findCityProductProfitListLastMonthService(city2);
System.out.println(cityProductProfits2 + "+++++++++++++++++++++++++++==");
			DecimalFormat format = new DecimalFormat("0.00");			
			if(cityProductProfits != null) {
				for(CityProductProfit cityProductProfit: cityProductProfits) {
					cityProductProfit.setProfit(format.format(Double.parseDouble(cityProductProfit.getProfit())));
				}
				request.setAttribute("cityProductProfits", cityProductProfits);
			} 
			if(cityProductProfits2 != null){
				for(CityProductProfit cityProductProfit2: cityProductProfits2) {
					cityProductProfit2.setProfit(format.format(Double.parseDouble(cityProductProfit2.getProfit())));
				}
				request.setAttribute("cityProductProfits2", cityProductProfits2);
			}else{
				request.setAttribute("errMsg", "当前没有任何城市的人购买过产品！");
			}
		}
		return address;
	}
			


}
